﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Collections;

namespace UtilityLibrary.Http
{
	public class SetCookiesModel : ICookieModel
	{
		public SetCookiesModel(String domain)
		{
			_cookies = new CookieCollection();
			_domain = domain;
		}

		private CookieContainer _cookieContainer;
		private String _domain;

		private CookieCollection _cookies;
		public CookieCollection Cookies
		{
			get { return _cookies; }
		}

		public void SetCookies(HttpWebRequest request)
		{
			request.CookieContainer = new CookieContainer();
			request.CookieContainer.MaxCookieSize = 100;
			_cookieContainer = request.CookieContainer;
			if (_cookies.Count > 0)
			{
				foreach (Cookie cookie in _cookies)
				{
					request.CookieContainer.Add(request.RequestUri, new Cookie(cookie.Name, cookie.Value, "/", _domain));
				}
			}
		}

		public void GetCookies(HttpWebResponse response)
		{
			_cookies.Add(GetAllCookies(_cookieContainer));
		}

		private CookieCollection GetAllCookies(CookieContainer cc)
		{
			CookieCollection lstCookies = new CookieCollection();

			Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
			    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
			    System.Reflection.BindingFlags.Instance, null, cc, new object[] { });

			foreach (object pathList in table.Values)
			{
				SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
				    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
				    | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
				foreach (CookieCollection colCookies in lstCookieCol.Values)
				{
					foreach (Cookie c in colCookies)
					{
						lstCookies.Add(c);
					}
				}
			}

			return lstCookies;
		}
	}
}
